<?php
namespace app\admin\model;

use think\Model;

class Category extends Model
{

    public function index()
    {}

    public function catetree()
    {
        $data = $this->select();
        return $this->resort($data);
    }

    public function resort($data, $parentid = 0, $level = 0)
    {
        static $ret = array();
        foreach ($data as $k => $v) {
            if ($v['parentid'] == $parentid) {
                $v['level'] = $level;
                $ret[] = $v;
                $this->resort($data, $v['cate_id'], $level + 1);
            }
        }
        
        return $ret;
    }

    public function chilrenid($cateid)
    {
        $data = $this->select();
        return $this->getchilrenid($data, $cateid);
    }

    public function getchilrenid($data, $parentid)
    {
        static $ret = array();
        foreach ($data as $k => $v) {
            if ($v['parentid'] == $parentid) {
                $ret[] = $v['cate_id'];
                $this->getchilrenid($data, $v['cate_id']);
            }
        }
        
        return $ret;
    }

    public function _before_delete($options)
    {
        if (is_array($options['where']['cate_id'])) {
            $arr = explode(',', $options['where']['cate_id'][1]);
            $soncates = array();
            foreach ($arr as $k => $v) {
                $soncates2 = $this->chilrenid($v);
                $soncates = array_merge($soncates, $soncates2);
            }
            $soncates = array_unique($soncates);
            $soncates = implode(',', $soncates);
            if ($soncates) {
                $this->execute("delete from ar_category where cate_id in ($soncates)");
            }
        } else {
            $chilrenids = $this->chilrenid($options['where']['cate_id']);
            $chilrenids = implode(',', $chilrenids);
            if ($chilrenids) {
                $this->execute("delete from ar_category where cate_id in ($chilrenids)");
            }
        }
    }
}